package com.douyin_spider.webmagic.downloader;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpResponseFactory;
import org.apache.http.entity.StringEntity;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import us.codecraft.webmagic.Page;
import us.codecraft.webmagic.Request;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.downloader.HttpClientDownloader;

import java.io.*;
import java.util.HashMap;

public class ImageDownloader extends HttpClientDownloader {

    @Override
    protected Page handleResponse(Request request, String charset, HttpResponse httpResponse, Task task) throws IOException {
        if (httpResponse.getHeaders("Content-Type").length != 0 &&
            httpResponse.getHeaders("Content-Type")[0].getValue().contains("image")
        ) {
            String origin_uri = request.<HashMap<String, String>>getExtra("map").get("origin_uri");
            StringEntity stringEntity = new StringEntity("123");
//            ResponseEntity<String> stringResponseEntity = new ResponseEntity<>("123", HttpStatus.OK);
////            httpResponse.setEntity(stringEntity);
            HttpEntity entity = httpResponse.getEntity();
            try (BufferedInputStream isr = new BufferedInputStream(entity.getContent());
                 FileOutputStream fos = new FileOutputStream("/Users/a58/backend/emoji_spider/emoji_image/" + origin_uri)) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = isr.read(buffer))!= -1) {
                    fos.write(buffer, 0, bytesRead);
                }
                System.out.println("图片下载完成" + origin_uri);
            }
        }

        return super.handleResponse(request, charset, httpResponse, task);
    }
}
